// 中选药品全院完成情况
import React, { useEffect } from "react";
import { VbpStatsByHisCodeI } from "../../../types";
import dayjs from "dayjs";

import * as d3 from "d3";

interface PropsI {
  data: VbpStatsByHisCodeI[];
}

const BarChartByHisCode: React.FC<PropsI> = (props: PropsI) => {
  var { data } = props;
  // const data = [
  //   {
  //     hisCode: "800036",
  //     drugname: "吡嗪酰胺片",
  //     startDate: "2022-03-01T00:00:00",
  //     amountSum: 8101,
  //     dutyAmount: 30000,
  //     percent: 0.27003333333333335,
  //   },
  //   {
  //     hisCode: "800424",
  //     drugname: "蒙诺(福辛普利钠片)",
  //     startDate: "2021-08-01T00:00:00",
  //     amountSum: 13307,
  //     dutyAmount: 90000,
  //     percent: 0.14785555555555555,
  //   },
  //   {
  //     hisCode: "800643",
  //     drugname: "开同(复方α-酮酸片)",
  //     startDate: "2021-08-01T00:00:00",
  //     amountSum: 111624,
  //     dutyAmount: 90000,
  //     percent: 1.2402666666666666,
  //   },
  //   {
  //     hisCode: "800650",
  //     drugname: "拜唐苹(阿卡波糖片)",
  //     startDate: "2021-08-01T00:00:00",
  //     amountSum: 570174.9800033569,
  //     dutyAmount: 90000,
  //     percent: 6.335277555592855,
  //   },
  //   {
  //     hisCode: "801334",
  //     drugname: "法安明(达肝素钠注射液)",
  //     startDate: "2021-08-01T00:00:00",
  //     amountSum: 27250,
  //     dutyAmount: 90000,
  //     percent: 0.30277777777777776,
  //   },
  // ];

  const refChart = React.useRef(null);

  useEffect(() => {
    if (refChart && refChart.current && data && data.length) {
      const node = refChart.current;
      const margin = { top: 50, right: 200, bottom: 30, left: 50 };

      const sortedData = d3.sort(data, (a, b) =>
        // d3.ascending(a.percent, b.percent)
        d3.descending(a.percent, b.percent)
      );

      // 矩形所占的宽度（包含空白），单位为像素
      var rectStep = 35;
      const width = 1280;
      const height = rectStep * data.length + margin.top + margin.bottom;
      d3.select(node).select("svg").remove();
      var svg = d3
        .select(node)
        .append("svg")
        .attr("width", width)
        .attr("height", height)
        .attr("viewBox", [0, 0, width, height]) // 后续rect等图是相对viewBox计算的，viewBox可随svg绽放
        .attr("style", "max-width: 100%; height: auto;");

      const xScale = d3
        .scaleLinear()
        .domain([
          0,
          d3.max(sortedData, (d: VbpStatsByHisCodeI) => d.percent) || 1,
        ])
        .range([0, width - margin.left - margin.right]);

      const yScale = d3
        .scaleBand()
        .domain(sortedData.map((d) => d.hisCode))
        .range([0, height - margin.top - margin.bottom])
        .padding(0.1);

      // 添加 x 轴
      svg
        .append("g")
        .attr("transform", `translate(${margin.left}, ${margin.top})`)
        .call(d3.axisTop(xScale));

      // 添加 y 轴
      svg
        .append("g")
        .attr("transform", `translate(${margin.left}, ${margin.top})`)
        .call(d3.axisLeft(yScale).tickSize(0))
        .selectAll("text")
        .remove();

      // 添加坐标轴标签
      svg
        .append("text")
        .attr("class", "x-label")
        .attr("text-anchor", "end")
        .attr("x", margin.left + (width - margin.left - margin.right) / 2) // 横坐标标签居中
        .attr("y", 20) // 位于 x 轴下方
        .text("完成比例");

      // console.log(margin.top + (height - margin.top - margin.bottom) / 2);

      svg
        .append("text")
        .attr("class", "y-label")
        .attr("text-anchor", "middle")
        .attr("transform", "rotate(-90)") // 旋转 90 度；旋转后x, y属性也受影响
        .attr("x", -(margin.top + (height - margin.top - margin.bottom) / 2)) // 横坐标标签居中
        .attr("y", 30) // 向上偏移
        .text("药品");

      // 绘制柱状图
      svg
        .selectAll(".bar")
        .data(d3.sort(sortedData, (a, b) => d3.ascending(a.percent, b.percent)))
        .enter()
        .append("rect")
        .attr("transform", `translate(${margin.left}, ${margin.top})`)
        .attr("class", "bar")
        .attr("x", 0)
        .attr("y", (d: any) => yScale(d.hisCode) || "")
        .attr("width", (d: any) => xScale(d.percent))
        .attr("height", yScale.bandwidth())
        // .attr("fill", (d) => d3.interpolateLab("red", "green")(d.percent));
        // .attr("fill", (d) => d3.interpolateRgb("red", "green")(d.percent));
        .attr("fill", (d) =>
          d3.interpolateRgbBasis(["red", "orange", "green"])(d.percent)
        );

      // 添加标签
      svg
        .selectAll(".label")
        .data(sortedData)
        .enter()
        .append("text")
        .attr("transform", `translate(${margin.left}, ${margin.top})`)
        .attr("class", "label")
        .attr("x", (d) => xScale(d.percent) + 5)
        .attr("y", (d) => yScale(d.hisCode)! + yScale.bandwidth() / 2)
        .attr("dy", "0.35em")
        .text(
          (d) =>
            `${d.drugname} ${dayjs(d.startDate).format("YYYY-MM-DD")} ${(
              d.percent * 100
            ).toFixed(2)} %`
        );
    }
    // 清除副作用
    return () => {
      d3.select(refChart.current).selectAll("*").remove();
    };
  }, [refChart, data]);

  return (
    <div>
      <div ref={refChart}></div>
    </div>
  );
};

export default BarChartByHisCode;
